/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-02-20
 * Time: 20:11
 */
//开散列，哈希桶
public class HashBuck {
    static class Node {
        public int key;
        public int val;

        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array = new Node[10];
    public int usedSize;
    public static final double  LOAD_FACTOR = 0.75; //负载因子最大值

    public void push(int key, int val) {
        Node node = new Node(key, val);
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                //更新val
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(doLoadFactor() >= 0.75) {
            //处理了 重新哈希
            reSize();
        }
    }
    private double doLoadFactor() {
        return usedSize*1.0 / array.length;
    }
    private void reSize() {
        Node[] newArray = new Node[array.length*2];
        //处理重新哈希
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int index = cur.key % newArray.length;
                //记录下来 之前的cur.next 不然修改后就找不到cur.next了
                Node curNext = cur.next;

                //进行头插法,插入到新数组
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;

                //尾插法
                /*Node cur2 = newArray[index];
                if(cur2 == null) {
                    newArray[index] = cur;
                } else {
                    while(cur2.next != null){
                        cur2 = cur2.next;
                    }
                        cur2.next = cur;
                }
                cur = curNext;*/
            }
        }
            //把数据给到原数组 array
            array = newArray;
        }
    public int get(int key) {
        //1、找到位置
        int index = key % array.length;
        //2、遍历数组
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }

        return -1;
    }
}
